<template>
  <div class="history-container">
    <div class="history-header">
      <h1>我的收藏</h1>
      <div class="search-box">
        <el-input
          type="text"
          v-model="queryForm.name"
          :suffix-icon="Search"
          placeholder="搜索更多收藏会话"
          @input="handleSearch"
        />
      </div>
    </div>

    <div class="history-content">
      <div v-for="(group, date) in groupedHistory" :key="date" class="history-group">
        <div class="date-header">{{ date }}</div>
        <div
          v-for="item in group"
          :key="item.id"
          class="history-item"
          @click="handleHistoryClick(item)"
        >
          <div class="item-content">
            <div class="item-text">{{ item.name }}</div>
            <div class="item-time">{{ item.create_time }}</div>
          </div>
          <div class="item-actions">
            <div class="item-time">{{ item.content }}</div>
            <div class="flex">
              <div>
                <img
                  src="../assets/10.png"
                  v-if="item.is_collected == false"
                  alt=""
                  @click.stop="handlefavorite(item)"
                />
                <img
                  src="../assets/10-1.png"
                  v-else
                  alt=""
                  @click.stop="handlefavorite(item)"
                />
              </div>
              <div>
                <img
                  src="../assets/11.png"
                  v-if="item.isedit != true"
                  alt=""
                  @click.stop="handleedit(item)"
                />
                <img
                  src="../assets/11-1.png"
                  v-else
                  alt=""
                  @click.stop="handleedit(item)"
                />
              </div>
              <!-- <div>
                <img
                  src="../assets/12.png"
                  @click.stop="handleDelete(item)"
                  v-if="item.isdel != true"
                  alt=""
                />
                <img src="../assets/12-1.png" v-else alt="" />
              </div> -->
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="queryForm.page"
      :layout="layout"
      :page-size="queryForm.count"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { Calendar, Search, Star, EditPen, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Collected, renSession, delSession, getcollectedList } from "../api/home.js";

const router = useRouter();
const searchQuery = ref("");
const total = ref(0);
const queryForm = ref({
  page: 1,
  count: 10,
  name: "",
});
const layout = ref("total, sizes, prev, pager, next, jumper");

// 模拟历史记录数据
const historyData = ref([]);

// 按日期分组的计算属性
const groupedHistory = computed(() => {
  const now = new Date(); //今天
  const now1 = new Date(); // 昨天
  const now2 = new Date(); // 七天内
  const now3 = new Date(); // 三十天内 
  now1.setDate(now1.getDate() - 1);
  now2.setDate(now2.getDate() - 7);
  now3.setDate(now3.getDate() - 30);
  // 今天
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
  const day = String(now.getDate()).padStart(2, "0"); // 日期需要两位数表示
  const today = year + "-" + month + "-" + day;
  // 昨天
  const year1 = now1.getFullYear();
  const month1 = String(now1.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
  const day1 = String(now1.getDate()).padStart(2, "0"); // 日期需要两位数表示
  const yesterday = year1 + "-" + month1 + "-" + day1;
  // 七天内
  const year2 = now2.getFullYear();
  const month2 = String(now2.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
  const day2 = String(now2.getDate()).padStart(2, "0"); // 日期需要两位数表示
  const sevendays = year2 + "-" + month2 + "-" + day2;
  // 三十天内
  const year3 = now3.getFullYear();
  const month3 = String(now3.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
  const day3 = String(now3.getDate()).padStart(2, "0"); // 日期需要两位数表示
  const thirtydays = year3 + "-" + month3 + "-" + day3;

  const filtered = historyData.value.filter((item) =>
    item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
  return filtered.reduce((groups, item) => {
    if (item.date == today || item.date == "今天") {
      item.date = "今天";
    } else if (item.date == yesterday || item.date == "昨天") {
      item.date = "昨天";
    } else if (
      new Date(Date.parse(item.date)) > new Date(Date.parse(sevendays)) ||
      item.date == "七天内"
    ) {
      item.date = "七天内";
    } else if (
      new Date(Date.parse(item.date)) > new Date(Date.parse(thirtydays)) ||
      item.date == "三十天内"
    ) {
      item.date = "三十天内";
    } else {
      item.date = item.date.slice(0, 7);
    }
    if (!groups[item.date]) {
      groups[item.date] = [];
    }
    groups[item.date].push(item);
    return groups;
  }, {});
});

// 处理搜索
const handleSearch = () => {
  // 实现搜索逻辑
  getphrasesList();
};

const handleCurrentChange = (val) => {
  queryForm.value.page = val;
  getphrasesList();
};

const handleSizeChange = (val) => {
  queryForm.value.count = val;
  getphrasesList();
};

// 处理历史记录点击
const handleHistoryClick = (item) => {
  // 导航到对话页面并传递对话内容
  router.push({
    name: "favoritedes",
    state: { content: item.content },
    query: {
      id: item.id,
    },
  });
};

// 处理删除
const handleDelete = (item) => {
  item.isdel = true;
  ElMessageBox.confirm("确定要删除这条历史记录吗?", "删除", {
    confirmButtonText: "确定", // 确认按钮文本
    cancelButtonText: "取消", // 取消按钮文本
  })
    .then(async () => {
      const res = await delSession(item.id);
      if (res.code == 0) {
        historyData.value = historyData.value.filter((i) => i.id !== item.id);
        ElMessage.success("操作成功");
        getphrasesList();
      } else {
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {
      item.isdel = false;
      // catch error
    });
};

// 处理收藏
const handlefavorite = async (item) => {
  const res = await Collected(item.id);
  if (res.code == 0) {
    item.is_collected = !item.is_collected;
    ElMessage.success("操作成功");
  } else {
    ElMessage.error("操作失败");
  }
};

// 重命名
const handleedit = async (item) => {
  ElMessageBox.prompt("请输入新的名称", "重命名", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async ({ value }) => {
      const res = await renSession(item.id, { name: value });
      if (res.code == 0) {
        ElMessage.success("操作成功");
        getphrasesList();
      } else {
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {});
};

// 获取会话列表
const getphrasesList = async () => {
  const res = await getcollectedList(queryForm.value.page - 1, queryForm.value.count, {
    name: queryForm.value.name,
  });
  if (res.code == 0) {
    res.data.items.forEach((item) => {
      item.date = item.create_time.split("T")[0];
      item.create_time = item.create_time.split(".")[0].replace("T", " ");
    });
    historyData.value = res.data.items;
    total.value = res.data.total;
  } else {
    historyData.value = [];
  }
};

onMounted(() => {
  getphrasesList();
});
</script>

<style scoped>
.history-container {
  max-width: 1000px;
  margin: 0 auto;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 26px;
  margin-top: 60px;
  font-family: Source Han Sans, Source Han Sans;
  font-weight: 700;
  font-size: 24px;
  color: #3d3d3d;
  line-height: 35px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.history-header h1 {
  font-size: 24px;
  color: #333;
}

:deep().el-input__wrapper {
  padding: 8px 16px;
  border: 0 !important;
  border-radius: 20px;
  width: 425px;
  height: 40px;
  font-size: 14px;
}

:deep().el-input__wrapper:focus {
  outline: none;
}

:deep().el-button {
  outline: none !important;
}

.history-group {
  margin-bottom: 26px;
}

.date-header {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  text-align: left;
}

.history-item {
  /* display: flex;
  justify-content: space-between; */
  align-items: center;
  padding: 24px 20px;
  background: white;
  border: 1px solid #8cdcdc;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.item-text {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 14px;
  color: #333333;
  line-height: 14px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.item-time {
  font-size: 12px;
  color: #999;
  align-items: center;
  display: flex;
}

.flex {
  display: flex;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 400;
  font-size: 12px;
  color: #999999;
  line-height: 12px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin-top: 10px;
}

.item-actions img {
  margin-left: 20px;
  width: 16px;
  height: 16px;
}

.action-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.action-btn:hover {
  color: #1a73e8;
}
</style>
